package com.z.utils.weixin.sdk.common.util.http;

import com.z.utils.DateUtilsMzywx;
import com.z.utils.IOUtil;
import com.z.utils.frame.util.HttpClientUtils;
import com.z.utils.property.CommonPropertyUtil;
import com.z.utils.weixin.sdk.common.api.IWxConfig;
import com.z.utils.weixin.sdk.common.bean.result.WxError;
import com.z.utils.weixin.sdk.common.exception.WxErrorException;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;

import java.io.IOException;
import java.util.Date;

/**
 * 简单的GET请求执行器，请求的参数是String, 返回的结果也是String
 *
 * @author springrain
 */
public class SimpleGetRequestExecutor implements RequestExecutor<String, String> {

  @Override
  public String execute(IWxConfig wxconfig, String uri, String queryParam) throws WxErrorException, IOException {
    if (queryParam != null) {
      if (uri.indexOf('?') == -1) {
        uri += '?';
      }
      uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
    }
    HttpGet httpGet = new HttpGet(uri);
    if (wxconfig.getHttpProxyHost()!=null) {
//      RequestConfig config = RequestConfig.custom().setProxy(new HttpHost(wxconfig.getHttpProxyHost(), wxconfig.getHttpProxyPort())).build();
//      if (uri.contains("/cgi-bin/user/getuserinfo?code=")) {//如果是获取 人员信息时减少超时时间
//    	  RequestConfig.custom().setc
//      }
//      httpGet.setConfig(config);
        if (uri.contains("/cgi-bin/user/getuserinfo?code=")) {//如果是获取 人员信息时减少超时时间
            int expireTime = 15000;
            try {
        		expireTime = Integer.valueOf(CommonPropertyUtil.getValue("rztime"));
        	} catch (NumberFormatException e) {
        		e.printStackTrace();
        	}
            if (expireTime < 0) {
            	expireTime = 10000;
            }
        	RequestConfig config = RequestConfig.custom().setProxy(new HttpHost(wxconfig.getHttpProxyHost(), wxconfig.getHttpProxyPort()))
        			.setConnectionRequestTimeout(expireTime).setConnectTimeout(expireTime).setSocketTimeout(expireTime).build();
            httpGet.setConfig(config);
        } else {
        	RequestConfig config = RequestConfig.custom().setProxy(new HttpHost(wxconfig.getHttpProxyHost(), wxconfig.getHttpProxyPort())).build();
            httpGet.setConfig(config);
        }
    } else if (uri.contains("/cgi-bin/user/getuserinfo?code=")) {//如果是获取 人员信息时减少超时时间
        int expireTime = 15000;
        try {
    		expireTime = Integer.valueOf(CommonPropertyUtil.getValue("rztime"));
    	} catch (NumberFormatException e) {
    		e.printStackTrace();
    	}
        if (expireTime < 0) {
        	expireTime = 10000;
        }
    	RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(expireTime).setConnectTimeout(expireTime).setSocketTimeout(expireTime).build();
        httpGet.setConfig(config);
    }
    String logFileName;
    if (uri.contains("/cgi-bin/user/getuserinfo?code=")) {//如果是获取 人员信息时减少超时时间
  	  logFileName = "loginLog_" + DateUtilsMzywx.convertDate2String(new Date()) + ".log";
    } else {
  	  logFileName = "myTest/getwxhttp"+DateUtilsMzywx.convertDate2String("yyyyMM", new Date())+".log";
    }
    String timeNow = "["+DateUtilsMzywx.convertDate2String("dd HH:mm:ss:SSS", new Date())+"]";
     String responseContent = HttpClientUtils.sendHttpGet(httpGet);
	 IOUtil.writeFLine(logFileName, "["+DateUtilsMzywx.convertDate2String("dd HH:mm:ss:SSS", new Date())+"]"+timeNow+responseContent+"\r\n");
      int i = 0;
      if (!uri.contains("/cgi-bin/user/getuserinfo?code=")) {
          while (responseContent == null && i < 5) {
        	  responseContent = HttpClientUtils.sendHttpGet(httpGet);
        	  i++;
        	  IOUtil.writeFLine(logFileName, "["+DateUtilsMzywx.convertDate2String("dd HH:mm:ss:SSS", new Date())+"]"+timeNow+"连接超时第"+i+"次重试\r\n");
        	  if (responseContent != null) {
            	  IOUtil.writeFLine(logFileName, "["+DateUtilsMzywx.convertDate2String("dd HH:mm:ss:SSS", new Date())+"]"+timeNow+responseContent+"\r\n");
        	  }
          }
          if (responseContent == null || responseContent.isEmpty()) {
              throw new WxErrorException(
                  WxError.newBuilder().setErrorCode(9999).setErrorMsg("无响应内容")
                      .build());
            }
      } else {
          int retryt = 3;
          try {
        	  retryt = Integer.valueOf(CommonPropertyUtil.getValue("rzretryt"));
      	  } catch (NumberFormatException e) {
      		  e.printStackTrace();
      	  }
          while (responseContent == null && i < retryt) {
        	  responseContent = HttpClientUtils.sendHttpGet(httpGet);
        	  i++;
        	  IOUtil.writeFLine(logFileName, "["+DateUtilsMzywx.convertDate2String("dd HH:mm:ss:SSS", new Date())+"]"+timeNow+"连接超时第"+i+"次重试\r\n");
        	  if (responseContent != null) {
            	  IOUtil.writeFLine(logFileName, "["+DateUtilsMzywx.convertDate2String("dd HH:mm:ss:SSS", new Date())+"]"+timeNow+responseContent+"\r\n");
        	  }
          }
          if (responseContent == null || responseContent.isEmpty()) {
              throw new WxErrorException(
                  WxError.newBuilder().setErrorCode(9999).setErrorMsg("无响应内容")
                      .build());
         }
      }

      if (responseContent.startsWith("<xml>")) {
        //xml格式输出直接返回
        return responseContent;
      }
      WxError error = WxError.fromJson(responseContent);
      if (error.getErrorCode() != 0) {
        throw new WxErrorException(error);
      }
      return responseContent;
  }

}
